export default {
  namespaced: true,
  state:() => ({
    // 购物车数组
    // 商品信息
    // {goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
    cart:JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations:  {
    addToCart(state,goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    // 删除购物车
    removeCartList(state,i) {
      state.cart.splice(i,1)
      this.commit('m_cart/saveToStorage')
    },
    // 全选与反选
    updateAllState(state,newState) {
      state.cart.forEach(item => {
        item.goods_state = newState
      })
      this.commit('m_cart/saveToStorage')
    }
    
  },
  getters: {
    total(state) {
     return state.cart.reduce((sum,item) => sum + item.goods_count,0)
    },
    // 勾选商品的数量
    checkCount(state) {
    return state.cart.filter(item => item.goods_state).reduce((sum,good) => sum + good.goods_count,0)
    },
    checkGoodsAmount(state) {
    return  state.cart.filter(item => item.goods_state).reduce((sum,item2) => sum + (item2.goods_count * item2.goods_price),0).toFixed(2)
    }
  }
}